﻿using Basic.FormCollect;
using Basic.FormModel.DB;
using Basic.FormRemoteModel.PhysicalGroup.Model;
using Basic.FormService.Interface;
using WeDonekRpc.Client;
using WeDonekRpc.Helper;
using WeDonekRpc.Model;

namespace Basic.FormService.lmpl
{
    internal class PhysicalGroupService : IPhysicalGroupService
    {
        private readonly IPhysicalFormGroupCollect _PhyGroup;
        private readonly ICustomFormCollect _CustomForm;

        public PhysicalGroupService ( IPhysicalFormGroupCollect phyGroup, ICustomFormCollect customForm )
        {
            this._PhyGroup = phyGroup;
            this._CustomForm = customForm;
        }

        public long Add ( PhysicalGroupSet obj )
        {
            return this._PhyGroup.Add(obj);
        }

        public void Delete ( long id )
        {
            if ( this._CustomForm.CheckIsUse(id) )
            {
                throw new ErrorException("form.physical.group.already.use");
            }
            DBPhysicalFormGroup source = this._PhyGroup.Get(id);
            this._PhyGroup.Delete(source);
        }

        public PhyGroupItem[] GetEnables ()
        {
            return this._PhyGroup.GetEnables<PhyGroupItem>();
        }
        public PhyGroupData Get ( long id )
        {
            DBPhysicalFormGroup source = this._PhyGroup.Get(id);
            return source.ConvertMap<DBPhysicalFormGroup, PhyGroupData>();
        }
        public PagingResult<PhyGroupDto> Query ( PhysicalGroupQuery query, IBasicPage paging )
        {
            DBPhysicalFormGroup[] list = this._PhyGroup.Query<DBPhysicalFormGroup>(query, paging, out int count);
            if ( list.IsNull() )
            {
                return new PagingResult<PhyGroupDto>(count);
            }
            Dictionary<long, int> useNum = this._CustomForm.GetPhyGroupUseNum(list.ConvertAll(a => a.Id));
            PhyGroupDto[] dto = list.ConvertMap<DBPhysicalFormGroup, PhyGroupDto>();
            dto.ForEach(a =>
            {
                a.UseNum = useNum.GetValueOrDefault(a.Id);
            });
            return new PagingResult<PhyGroupDto>(dto, count);
        }

        public bool Set ( long id, PhysicalGroupSet obj )
        {
            DBPhysicalFormGroup source = this._PhyGroup.Get(id);
            return this._PhyGroup.Set(source, obj);
        }

        public void SetIsEnable ( long id, bool isEnable )
        {
            DBPhysicalFormGroup source = this._PhyGroup.Get(id);
            this._PhyGroup.SetIsEnable(source, isEnable);
        }
    }
}
